import React, { useEffect, useRef, useState } from 'react';
import { Modal } from 'antd';
import { useDispatch, useSelector } from 'umi';
import QrCode from 'qrcode.react';
import Loading from '@/components/Loading';
import styles from './index.less';

export default ({ visible, amount = 0.0, type = 'alipay', onClose }) => {
    onClose = onClose || function() {};
    const dispatch = useDispatch();
    const timeout = useRef();
    const [error, setError] = useState();
    const pay = useSelector(state => state.pay[type]);

    const { id, qr } = pay || {};
    let { status } = pay || {};
    useEffect(() => {
        if (visible) {
            dispatch({
                type: `pay/${type}Precreate`,
                payload: {
                    amount,
                },
            }).then(({ result, ...res }) => {
                if (!result) {
                    setError(res.message);
                }
            });
        }
    }, [visible, amount, type, dispatch]);

    useEffect(() => {
        if (id) {
            const query = () => {
                dispatch({
                    type: `pay/${type}Query`,
                    payload: {
                        id,
                    },
                }).then(({ result, ...res }) => {
                    if (!result) {
                        clearInterval(timeout.current);
                        setError(res.message);
                    }
                });
            };
            timeout.current = setInterval(query, 3000);
        }
        return () => {
            clearInterval(timeout.current);
        };
    }, [id, dispatch]);
    status = status ? status.toLowerCase() : null;

    useEffect(() => {
        if (status === 'succeed' && timeout.current) {
            clearInterval(timeout.current);
            timeout.current = null;
            // 清除支付状态
            dispatch({
                type: `pay/set${type.charAt(0).toUpperCase() + type.slice(1)}`,
                payload: {
                    status: 'default',
                },
            });
            dispatch({
                type: 'user/setBank',
                payload: {
                    append: true,
                    cash: amount,
                },
            });
            onClose('succeed');
        }
    }, [dispatch, type, status, onClose]);

    const render = () => {
        if (error) return <p>出错了,{error}</p>;
        if (!qr) return <Loading />;
        if (status === 'faild') return <p>支付失败</p>;
        return (
            <>
                <div className={styles['title']}>
                    <p className={styles['desc']}>扫一扫付款(元)</p>
                    <p className={styles['amount']}>{amount}</p>
                </div>
                <div className={styles['qr-code']}>
                    <QrCode
                        value={qr}
                        renderAs="svg"
                        includeMargin={true}
                        size={258}
                        level="Q"
                        imageSettings={{
                            src:
                                '',
                            x: null,
                            y: null,
                            height: 42,
                            width: 42,
                            excavate: true,
                        }}
                    />
                </div>
                <div className={styles['footer']}>打开手机支付宝，扫一扫付款</div>
            </>
        );
    };

    return (
        <Modal
            wrapClassName={styles['warpper']}
            title="扫码支付"
            visible={visible}
            footer={null}
            width={500}
            onCancel={onClose}
        >
            {render()}
        </Modal>
    );
};
